
const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const OSS = require('ali-oss');

const client = new OSS({
  region: 'oss-cn-hangzhou',  
  accessKeyId: 'id',
  accessKeySecret: 'secret',
  bucket: 'bucket',
});

const upload = multer({ dest: 'uploads/' });

router.post('/upload', upload.single('image'), async (req, res) => {

  if (!req.file) {
    return res.status(400).send('请选择上传文件');
  }

  const uploadedImage = req.file;
  const originalName = path.basename(uploadedImage.originalname, path.extname(uploadedImage.originalname));
  const fileExtension = path.extname(uploadedImage.originalname);
  const fileName = `flutter/${Date.now()}${fileExtension}`;

  try {
    const result = await client.put(fileName, uploadedImage.path);
    res.send({
      message: '图片上传成功！',
      url: result.url,
    });
  } catch (err) {
    console.error(err);
    res.status(500).send('图片上传失败');
  }
});

module.exports = router;